package kr.hkit.powerjava.chapter23;

class Counter {
	private int value = 0;

	public void increment() {
		value++;
	}

	public void decrement() {
		value--;
	}

	public void printCounter() {
		System.out.println(value);
	}
}

class sharedThread extends Thread {
	Counter sharedThread;

	public sharedThread(Counter c) {
		this.sharedThread = c;
	}

	@Override
	public void run() {
		int i = 0;
		while (i < 20000) {
			sharedThread.increment();
			sharedThread.decrement();
			if (i % 40 == 0) {
				sharedThread.printCounter();
				try {
					sleep((int) (Math.random() * 2));
				} catch (InterruptedException e) {
				}
			}
			i++;
		}
	}
}

public class CounterTest {
	public static void main(String[] args) {
		Counter c = new Counter();
		new sharedThread(c).start();
		new sharedThread(c).start();
		new sharedThread(c).start();
		new sharedThread(c).start();
	}
}
